package com.dcshop.demo.controller;//package com.xbox.consumer.controller;


import com.github.ontio.OntSdk;
import com.github.ontio.sdk.wallet.Account;
import com.github.ontio.sdk.wallet.Identity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * ontid账号注册
 */
@RestController
public class RegisterOntIdController extends AbsController {


    /**
     * 注册ontid
     *
     * @param reqMap
     * @return
     */
    @PostMapping("/registerOntId")
    public String registerOntId(@RequestBody Map<String, Object> reqMap) {

        String username = reqMap.get("username").toString();
        String password = reqMap.get("password").toString();

        if (StringUtils.isEmpty(username)) {
            return "fail";
        }
        if (StringUtils.isEmpty(password)) {
            return "fail";
        }

        OntSdk ontSdk = null;
        Identity identity = null;
        Account wltPayerAccount = null;
        try {
            ontSdk = getOntSdk();

            //创建钱包账号
            wltPayerAccount = ontSdk.getWalletMgr().createAccount(password);

            //支付交易费用的账户
            com.github.ontio.account.Account payerAccount = ontSdk.getWalletMgr().getAccount(wltPayerAccount.address, password, wltPayerAccount.getSalt());

            //创建ontId
            identity = ontSdk.getWalletMgr().createIdentity(password);

            //注册者指定支付交易费用的账户地址
            ontSdk.nativevm().ontId().sendRegister(identity, password, payerAccount, ontSdk.DEFAULT_GAS_LIMIT, 0);

            //创建的账号或身份只在内存中，如果要写入钱包文件，需调用写入接口
            ontSdk.getWalletMgr().writeWallet();

            //3. 查询链上身份信息
            //链上身份DDO信息，可以通过ONT ID进行查询。
            //通过ONT ID获取DDO
            String ddo = ontSdk.nativevm().ontId().sendGetDDO(identity.ontid);

            //TODO ontid 、wlt数据由用户保存

            //TODO username 和 ontid 映射关系存数据库

            saveToDb(username, identity.ontid);

            System.out.println("ddd===" + ddo);

            return identity.ontid;

        } catch (Exception e) {
            e.getMessage();
            return "error";
        }


    }

    /**
     * 保存数据库
     *
     * @param username
     * @param ontid
     */
    private void saveToDb(String username, String ontid) {

        //TODO

    }


}
